<template>
  <div class="">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="showRoles">添加角色</el-button>
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['vcenter','bdbottom',index1 === 0 ? 'bdtop' : '']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="['vcenter',index2 === 0 ? '' : 'bdtop']" v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id"
                      @close="removeRightById(scope.row,item3.id)">{{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" icon="el-icon-edit" @click="editRoles(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
            <el-button type="warning" size="small" icon="el-icon-setting" @click="showDialogVisible(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="分配权限" :visible.sync="DialogVisible" width="35%" @close="clear">
        <el-tree ref="tree" :data="rolesTree" :default-checked-keys="defaultKeys" default-expand-all node-key="id" show-checkbox :props="treeProps"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="DialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="RoleInfo">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="35%" @close="addDialogClear">
        <el-form :model="addRolesForm" status-icon :rules="rules" ref="addRolesForm" label-width="90px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="35%" @close="editDialogClear">
        <el-form :model="editRolesForm" status-icon :rules="rules" ref="editForm" label-width="90px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="updataRoles">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      DialogVisible: false,
      addDialogVisible: false,
      editDialogVisible: false,
      rolesTree: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defaultKeys: [],
      roleId: '',
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      editRolesForm: {
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getRoles () {
      const { data } = await this.$http.get('/roles')
      if (data.meta.status === 200) {
        this.rolesList = data.data
      } else {
        this.$message.error('获取角色信息失败')
      }
    },
    async removeRightById (role, rightId) {
      const result = await this.$confirm('您确认要删除该用户的权限嘛', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return this.$message.info('取消了删除')
      const { data } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (data.meta.status !== 200) return this.$message.error('删除权限失败')
      role.children = data.data
    },
    async showDialogVisible (role) {
      const { data } = await this.$http.get('rights/tree')
      if (data.meta.status !== 200) return this.$message.error('获取权限失败')
      this.rolesTree = data.data
      this.getLeafKeys(role, this.defaultKeys)
      this.roleId = role.id
      this.DialogVisible = !this.DialogVisible
    },
    showRoles () {
      this.addDialogVisible = true
    },
    async addRoles () {
      this.$refs.addRolesForm.validate(async valid => {
        if (valid) {
          const { data } = await this.$http.post('roles', this.addRolesForm)
          if (data.meta.status !== 201) return this.$message.error('添加角色失败')
          this.$message.success('添加角色成功')
          this.addDialogVisible = false
          this.getRoles()
        }
      })
    },

    async editRoles (role) {
      this.editDialogVisible = true
      const { data } = await this.$http.get(`roles/${role.id}`)
      if (data.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.editRolesForm = data.data
    },
    async updataRoles () {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          const { data } = await this.$http.put(`roles/${this.editRolesForm.roleId}`, this.editRolesForm)
          if (data.meta.status !== 200) return this.$message.error('更新用户信息失败')
          this.$message.success('更新角色成功')
          this.editDialogVisible = false
          this.getRoles()
        }
      })
    },

    async RoleInfo () {
      const keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysStr })
      if (data.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('保存成功')
      this.DialogVisible = !this.DialogVisible
      this.getRoles()
    },
    clear () {
      this.defaultKeys = []
    },
    addDialogClear () {
      this.$refs.addRolesForm.resetFields()
    },
    editDialogClear () {
      this.$refs.editForm.resetFields()
    },
    deleteRoles (id) {
      this.$confirm('是否永久删除该角色', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data } = await this.$http.delete(`roles/${id}`)
        if (data.meta.status !== 200) return this.$message.error(`${data.meta.msg}`)
        this.$message.success('删除成功!')
        this.getRoles()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    }
  },
  created () {
    this.getRoles()
  }
}
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
